<?php
class Api_oauth_openid{
    /**
     * 芦美广告公众号openid获取接口
     * 请求地址：http://bid999.com/api/oauth/openid?url=xxx
     */
    public function get(){
        //应用ID
        $appid = 'wx75d7dc5f9c92e40f';
        //应用密钥
        $secret = '488cc5a8b13d27c0b110c9756f5ca941';
        if(!isset($_GET['code'])){
            if(!isset($_GET['url'])){
                exit('url is empty');
            }else{
                $scope = 'snsapi_base';
                $state = $_GET['url'];
                $redirectUri = urlencode('http://bid999.com/api/oauth/openid');
                $wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirectUri . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
                header('Location:'.$wxUrl);
            }
        }else{
            $code = $_GET['code'];
            $state = $_GET['state'];
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
            $res = json_decode($this->httpGet($url));
            $openid = $res->openid;
            if(preg_match('/\?/', $state)){
                header('Location:'.$state.'&openid='.$openid);
            }else{
                header('Location:'.$state.'?openid='.$openid);
            }
        }
    }

    /**
     * CURL发送get请求
     * @param $url string 请求的url地址
     * @return mixed 对应url响应的数据
     */
    private function httpGet($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url );
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
        return curl_exec($curl);
    }
}